package com.example.randox;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import library.DatabaseHandler;
import library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MemberActivity  extends Activity  {

	private DatabaseHandler db;
	private HashMap<String, String> userDetails;
	private UserFunctions userFunction;
	private ImageView btnSearch;
	private ImageView switchStatus;
	private RotateAnimation animation;
	private  TextView messageWelcome;
	private  TextView messageStatus;
	
	private static String KEY_SUCCESS = "success";
	private static String KEY_IDCONVERSATION = "idConversation";
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_member);
		
        db = new DatabaseHandler(getApplicationContext());
        userDetails = db.getUserDetails();
        	 
		userFunction = new UserFunctions();
		 
		btnSearch=(ImageView)findViewById(R.id.imageView2);
		switchStatus=(ImageView)findViewById(R.id.imageView3);
		messageWelcome = (TextView)findViewById(R.id.textView1);
		messageStatus = (TextView)findViewById(R.id.textView2);
	
		messageWelcome.setText("Hello "+userDetails.get("firstname").toString()+", \nTouch here to start");	
		
		if(Integer.parseInt(userDetails.get("idStatus"))==1){
			switchStatus.setImageResource(R.drawable.online);
		}else{
			switchStatus.setImageResource(R.drawable.offline);
		}
		
		btnSearch.setOnClickListener(new View.OnClickListener() {
			    public void onClick(View v) {
			    	if(Integer.parseInt(userDetails.get("idStatus"))==1){
			    		MyCount timerCount = new MyCount(3 * 1000, 1000);
						timerCount.start();
						animation = new RotateAnimation(0f, 360f, btnSearch.getWidth()/2, btnSearch.getHeight()/2); 
				        animation.setInterpolator(new LinearInterpolator());
				        animation.setRepeatCount(Animation.INFINITE);
				        animation.setDuration(1700);
						btnSearch.startAnimation(animation);
						btnSearch.setEnabled(false);
			    	}else{
			    		 Toast.makeText(MemberActivity.this, "You are offline", Toast.LENGTH_SHORT).show();
			    	}
			    	
			    }
			});
		
		messageStatus.setOnClickListener(new View.OnClickListener() {
		    public void onClick(View v) {
		    	if(Integer.parseInt(userDetails.get("idStatus"))==1){
		    		JSONObject json = userFunction.updateStatus(2,userDetails.get("email").toString());
		    		try {
	                     if (json.getString(KEY_SUCCESS) != null) {
	                         String res = json.getString(KEY_SUCCESS); 
	                         if(Integer.parseInt(res) == 1){
	                        	 
	                         }else{
	                        	 
	                         }
	                     }
	                     } catch (JSONException e) {
		                     e.printStackTrace();
		                 }
		    		db.updateStatus(2,userDetails.get("email").toString());
			    	switchStatus.setImageResource(R.drawable.offline);
			    	messageStatus.setText("Offline");
			    	userDetails = db.getUserDetails();
		    	}else{
		    		JSONObject json = userFunction.updateStatus(1,userDetails.get("email").toString());
		    		try {
	                     if (json.getString(KEY_SUCCESS) != null) {
	                         String res = json.getString(KEY_SUCCESS); 
	                         if(Integer.parseInt(res) == 1){
	                        	 
	                         }else{

	                         }
	                     }
	                     } catch (JSONException e) {
		                     e.printStackTrace();
		                 }
		    		db.updateStatus(1,userDetails.get("email").toString());
			    	switchStatus.setImageResource(R.drawable.online);
			    	messageStatus.setText("Online");
			    	userDetails = db.getUserDetails();
		    	}
		    }
		});
	}
	
	
	 public class MyCount extends CountDownTimer {
	      public MyCount(long millisInFuture, long countDownInterval) {
	        super(millisInFuture, countDownInterval);
	      }

	      @Override
	      public void onFinish() {
	      animation.cancel();  
	    	  
	      JSONObject json = userFunction.checkConversation(userDetails.get("email").toString());
	         	try {
            if (json.getString(KEY_SUCCESS) != null) {
                String res = json.getString(KEY_SUCCESS); 
                if(Integer.parseInt(res) == 1){  
                		Intent i=new Intent(MemberActivity.this,ChatActivity.class);
                		i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                		startActivity(i);
                		finish();
                }else{
                	   JSONObject jsonSearch = userFunction.searchUser(userDetails.get("email".toString()), userDetails.get("sex".toString()));
          	         try {
                           if (jsonSearch.getString(KEY_SUCCESS) != null) {
                               String resSearch = jsonSearch.getString(KEY_SUCCESS); 
                               if(Integer.parseInt(resSearch) == 1){
                                   JSONObject json_user = jsonSearch.getJSONObject("user");
                                   db.updateConversation(json_user.getInt(KEY_IDCONVERSATION),userDetails.get("email").toString());
                                   Intent i = new Intent(MemberActivity.this, ChatActivity.class);
                                   i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                                   startActivity(i);
                                   finish();
                               }else{
                              	 Toast.makeText(MemberActivity.this, "The search returns no response", Toast.LENGTH_SHORT).show();
                               }
                           }
                       } catch (JSONException e) {
                           e.printStackTrace();
                       }
          	        btnSearch.setEnabled(true);
                }
            }
	         	} catch (JSONException e) {
      	  e.printStackTrace();
        	}
	    	  
 
	     
	      }

	      @Override
	      public void onTick(long millisUntilFinished) {
	        //some script here 
	      }   
	} 

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.logout:
			userFunction.logoutUser(getApplicationContext());
            Intent login = new Intent(getApplicationContext(), LoginActivity.class);
            login.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(login);
            finish();
	        return true;
	    default:
	        return super.onOptionsItemSelected(item);
	    }
	}


}
